package cn.bugio.note.rocketmq.user;

import cn.bugio.note.common.domain.messaging.UserAndBonusMsgDTO;
import cn.bugio.note.dao.user.BonusEventLogMapper;
import cn.bugio.note.dao.user.UserMapper;
import cn.bugio.note.domain.entity.user.BonusEventLog;
import cn.bugio.note.domain.entity.user.User;
import lombok.extern.slf4j.Slf4j;

import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author Vincent Vic
 * @version 1.0
 * @Description
 * @since 2021/3/1
 */
@Slf4j
@Component
public class AddBounsListenerStream {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BonusEventLogMapper bonusEventLogMapper;



    @StreamListener(MySink.TREK_INPUT)
    public void onTrekMessage(@Payload UserAndBonusMsgDTO message) {
        log.info("[onMessage][线程编号:{} 消息内容：{}]", Thread.currentThread().getId(), message);
    }

    @StreamListener(MySink.ERBADAGANG_INPUT)
    public void onMessage(@Payload UserAndBonusMsgDTO message) {

        log.info("[onMessage][线程编号:{} 消息内容：{}]", Thread.currentThread().getId(), message);
        //当收到消息的时候执行业务
        //1.为用户加积分
        log.info("接收消息 --> {}" ,message);

        if (message.getUserId() == null){
            return;
        }


        Integer userId = message.getUserId();
        User user = userMapper.selectByPrimaryKey(userId);
        Integer bonus = message.getBonus();
        user.setBonus(user.getBonus()+ bonus);
        userMapper.updateByPrimaryKeySelective(user);

        //2.记录日志到bouns_event
        BonusEventLog build1 = BonusEventLog.builder().userId(message.getUserId()).event("add " + bonus).build();
        bonusEventLogMapper.insert(
                BonusEventLog.builder()
                        .userId(userId)
                        .value(bonus)
                        .event("CONTRIBUTE")
                        .createTime(new Date())
                        .description("投稿添加积分")
                        .build()
        );

    }


    /**
     * 全局异常处理
     * @param message
     */
    @StreamListener("errorChannel")
    public void error(Message<?> message) {
        log.info("[onMessage][线程编号:{} 消息内容：{}]", Thread.currentThread().getId(), message);
    }
}
